import "./index.css";
import { useEffect, useState } from "react";
import { CloseOutlined } from "@ant-design/icons";
import { loginApi, registerApi } from "@/apis/user";
import { useDispatch } from "react-redux";
import { setToken } from "@/store/modules/userStore";
import { message } from "antd";
import Loader from "../loader";

export default function LoginRegister({
  isShowLoginRegister,
  setIsShowLoginRegister,
}: any) {
  const [isLogin, setIsLogin] = useState(true);
  const [isloading, setIsloading] = useState(false);

  useEffect(() => {
    hiddenBodyScroll();
    return () => {
      showBodyScroll();
      setIsLogin(true);
    };
  }, []);

  if (!isShowLoginRegister) return null;

  return (
    <>
      <div className="login-register-container">
        {isLogin ? (
          <Login
            isLogin={isLogin}
            setIsLogin={setIsLogin}
            setIsShowLoginRegister={setIsShowLoginRegister}
            setIsloading={setIsloading}
          >
            <CloseBtn setIsShowLoginRegister={setIsShowLoginRegister} />
          </Login>
        ) : (
          <Register
            isLogin={isLogin}
            setIsLogin={setIsLogin}
            setIsShowLoginRegister={setIsShowLoginRegister}
            setIsloading={setIsloading}
          >
            <CloseBtn setIsShowLoginRegister={setIsShowLoginRegister} />
          </Register>
        )}
      </div>
      {isloading && <Loader />}
    </>
  );
}

function Login({
  isLogin,
  setIsLogin,
  children,
  setIsShowLoginRegister,
  setIsloading,
}: any) {
  const dispatch = useDispatch();
  const [user, setUser] = useState({
    account: "",
    password: "",
  });

  async function login() {
    const formData = new FormData();
    formData.append("account", user.account);
    formData.append("password", user.password);

    try {
      setIsloading(true);
      const res: any = await loginApi(formData);
      if (res.code === 0) {
        message.success("登录成功");
        dispatch(setToken(res.data));
        // setIsShowLoginRegister(false);
      } else {
        message.error("登录失败，请检查账户或密码！");
        // alert(res.message);
      }
    } catch (error) {
      message.error("登录失败，请稍后重试！");
      console.error(error);
    } finally {
      setIsloading(false);
      setIsShowLoginRegister(false);
    }
  }

  if (!isLogin) return null;
  return (
    <>
      <div className="form-container">
        {children}
        <p className="title">登录</p>
        <form
          className="form"
          onSubmit={(e) => {
            e.preventDefault();
            login();
          }}
        >
          <div className="input-group">
            <label htmlFor="account">账户</label>
            <input
              autoFocus
              value={user.account}
              onChange={(e) => setUser({ ...user, account: e.target.value })}
              type="text"
              name="account"
              id="account"
            />
          </div>
          <div className="input-group">
            <label htmlFor="password">密码</label>
            <input
              value={user.password}
              onChange={(e) => setUser({ ...user, password: e.target.value })}
              type="password"
              name="password"
              id="password"
            />
            <div className="forgot">
              <a rel="noopener noreferrer" href="#">
                忘记密码 ？
              </a>
            </div>
          </div>
          <button className="sign" type="submit">
            登录
          </button>
        </form>
        <p className="signup">
          没有账号 ？
          <a
            rel="noopener noreferrer"
            onClick={() => setIsLogin(false)}
            className="icon"
          >
            注册
          </a>
        </p>
      </div>
    </>
  );
}

function Register({ isLogin, setIsLogin, children, setIsloading }: any) {
  const [user, setUser] = useState({
    account: "",
    username: "",
    email: "",
    password: "",
    confirmPassword: "",
  });

  async function register() {
    try {
      setIsLogin(true);
      const res: any = await registerApi(user);
      if (res.code === 0) {
        message.success("注册成功，请登录！");
        setIsLogin(true);
      } else {
        message.error("注册失败，请检查信息是否正确！");
      }
    } catch (error) {
      message.error("注册失败，请稍后重试！");
      console.error(error);
    } finally {
      setIsloading(false);
    }
  }

  if (isLogin) return null;
  return (
    <>
      <div className="form-container">
        {children}
        <p className="title">注册</p>
        <form
          className="form"
          onSubmit={(e) => {
            e.preventDefault();
            register();
          }}
        >
          <div className="input-group">
            <label htmlFor="account">账户</label>
            <input
              autoFocus
              value={user.account}
              onChange={(e) => setUser({ ...user, account: e.target.value })}
              type="text"
              name="account"
              id="account"
              placeholder="输入您的账户"
            />
          </div>
          <div className="input-group">
            <label htmlFor="username">用户名</label>
            <input
              value={user.username}
              onChange={(e) => setUser({ ...user, username: e.target.value })}
              type="text"
              name="username"
              id="username"
              placeholder="输入您的用户名"
            />
          </div>
          <div className="input-group">
            <label htmlFor="email">邮箱</label>
            <input
              type="email"
              name="email"
              id="email"
              placeholder="输入您的邮箱"
            />
          </div>
          <div className="input-group">
            <label htmlFor="password">密码</label>
            <input
              value={user.password}
              onChange={(e) => setUser({ ...user, password: e.target.value })}
              type="password"
              name="password"
              id="password"
              placeholder="输入密码"
            />
          </div>
          <div className="input-group">
            <label htmlFor="confirm-password">确认密码</label>
            <input
              type="password"
              name="confirm-password"
              id="confirm-password"
              placeholder="再次输入密码"
            />
          </div>
          <button className="sign" type="submit" style={{ marginTop: "2em" }}>
            注册
          </button>
        </form>
        <p className="signup">
          已有账号？
          <a
            rel="noopener noreferrer"
            onClick={() => setIsLogin(true)}
            className="icon"
          >
            登录
          </a>
        </p>
      </div>
    </>
  );
}

function CloseBtn({ setIsShowLoginRegister }: any) {
  return (
    <p
      style={{
        display: "flex",
        justifyContent: "flex-end",
        cursor: "pointer",
      }}
    >
      <CloseOutlined onClick={() => setIsShowLoginRegister(false)} />
    </p>
  );
}

function hiddenBodyScroll() {
  document.body.style.overflow = "hidden";
  document.body.style.paddingRight = "1em";
}

function showBodyScroll() {
  document.body.style.overflow = "";
  document.body.style.paddingRight = "";
}
